import 'dart:math';

class Snake {
  late List<Point<int>> body;
  late Point<int> direction;
  
  Snake() {
    body = [Point(5, 5)];
    direction = Point(1, 0); // 初始向右移动
  }
  
  void move() {
    // 创建新头部
    Point<int> newHead = Point(
      body.first.x + direction.x,
      body.first.y + direction.y,
    );
    
    body.insert(0, newHead);
    body.removeLast();
  }
  
  void grow() {
    // 蛇增长时不移除尾部
    Point<int> newHead = Point(
      body.first.x + direction.x,
      body.first.y + direction.y,
    );
    body.insert(0, newHead);
  }
  
  void changeDirection(Point<int> newDirection) {
    // 防止180度转向
    if (direction.x != -newDirection.x || direction.y != -newDirection.y) {
      direction = newDirection;
    }
  }
  
  bool checkCollision(Point<int> point) {
    return body.any((segment) => segment.x == point.x && segment.y == point.y);
  }
  
  bool checkSelfCollision() {
    final head = body.first;
    return body.skip(1).any((segment) => segment.x == head.x && segment.y == head.y);
  }
  
  void reset() {
    body = [Point(5, 5)];
    direction = Point(1, 0);
  }
}